// admin/dashboard/dashboard.js
const db = wx.cloud.database();
const _ = db.command;

Page({
  data: {
    stats: {
      totalOrders: 0,
      pendingOrders: 0,
      completedOrders: 0,
      totalIncome: 0,
    },
    loading: true,
  },

  onShow: function () {
    this.getStats();
  },

  getStats: function () {
    this.setData({ loading: true });
    wx.cloud.callFunction({
      name: 'getStats'
    }).then(res => {
      // --- *** 修改：增加失败处理 *** ---
      if (res.result.success) {
        this.setData({
          stats: res.result.stats,
          loading: false
        });
      } else {
        // 如果 success 为 false，显示云函数返回的 message
        wx.showToast({
          title: res.result.message || '加载失败',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
      // --- *** 修改结束 *** ---
    }).catch(err => {
      this.setData({ loading: false });
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      console.error('获取统计数据失败', err);
    });
  },

  onPullDownRefresh: function () {
    this.getStats();
    wx.stopPullDownRefresh();
  }
});